import { createStore } from 'vuex'
import { get } from '../utils/index'
// 创建一个新的 store 实例

interface State {
  token: string | null
  theme: string
  userName: string | null
  online: Array<any>
  msg: any
}

const store = createStore({
  state(): State {
    return {
      token: get('token'),
      theme: 'light', //dark light
      userName: get('userName'),
      // 在线人数
      online: [],
      // 消息列表
      msg: {},
    }
  },
  mutations: {
    setUserName(state: State, res) {
      state.userName = res
    },
    setToken(state: any, val: string) {
      state.token = val
    },
    setTheme(state: State) {
      state.theme === 'light' ? (state.theme = 'dark') : (state.theme = 'light')
    },
    setOnline(state: State, res) {
      state.online = res
    },
    setMsg(state: State, res: { from: string; msg: any; isSelf: boolean }) {
      if (state.msg[res.from]) {
        if (typeof res.msg === 'object') {
          if (res.msg.type === 'rec') {
            // if (!res.msg.blob) return
            if (typeof res.msg.blob === 'string') {
              state.msg[res.from].push({
                type: 'rec',
                msg: import.meta.env.VITE_API_URL + res.msg.blob,
                isSelf: res.isSelf || false,
              })
            } else {
              const url = window.URL.createObjectURL(res.msg.blob)
              state.msg[res.from].push({
                type: 'rec',
                msg: url,
                isSelf: res.isSelf || false,
              })
            }
          } else if (res.msg.type === 'image') {
            console.log(res.msg)

            state.msg[res.from].push({
              type: 'image',
              msg: res.msg.blob,
              isSelf: res.isSelf || false,
            })
          } else if (res.msg.type === 'video') {
            state.msg[res.from].push({
              type: 'video',
              msg: res.msg.blob,
              isSelf: res.isSelf || false,
            })
          } else if (res.msg.type === 'icon') {
            state.msg[res.from].push({
              type: 'icon',
              msg: res.msg.blob,
              isSelf: res.isSelf || false,
            })
          }
        } else {
          state.msg[res.from].push({
            type: 'text',
            msg: res.msg,
            isSelf: res.isSelf || false,
          })
        }
      } else {
        res.msg ? (state.msg[res.from] = [res.msg]) : (state.msg[res.from] = [])
      }
      console.log(state.msg, 'x')
    },
  },
  actions: {},
})

export default store
